package com.ideafactory.client.print;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.Toast;

import com.ideafactory.client.beans.OrderGoodsBean;
import com.ideafactory.client.utils.SpUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class PrintDataService {
    private Context context = null;
    private String deviceAddress = null;
    private BluetoothAdapter bluetoothAdapter = BluetoothAdapter
            .getDefaultAdapter();
    private BluetoothDevice device = null;
    private static BluetoothSocket bluetoothSocket = null;
    private static OutputStream outputStream = null;
    private static final UUID uuid = UUID
            .fromString("00001101-0000-1000-8000-00805F9B34FB");
    public static boolean isConnection = false;
    final String[] items = { "复位打印机", "标准ASCII字体", "压缩ASCII字体", "字体不放大",
            "宽高加倍", "取消加粗模式", "选择加粗模式", "取消倒置打印", "选择倒置打印", "取消黑白反显", "选择黑白反显",
            "取消顺时针旋转90°", "选择顺时针旋转90°" ,"左对齐","居中","右对齐"};
    final byte[][] byteCommands = { { 0x1b, 0x40 },// 复位打印机
            { 0x1b, 0x4d, 0x00 },// 标准ASCII字体
            { 0x1b, 0x4d, 0x01 },// 压缩ASCII字体
            { 0x1d, 0x21, 0x00 },// 字体不放大
            { 0x1d, 0x21, 0x11 },// 宽高加倍
            { 0x1b, 0x45, 0x00 },// 取消加粗模式
            { 0x1b, 0x45, 0x01 },// 选择加粗模式
            { 0x1b, 0x7b, 0x00 },// 取消倒置打印
            { 0x1b, 0x7b, 0x01 },// 选择倒置打印
            { 0x1d, 0x42, 0x00 },// 取消黑白反显
            { 0x1d, 0x42, 0x01 },// 选择黑白反显
            { 0x1b, 0x56, 0x00 },// 取消顺时针旋转90°
            { 0x1b, 0x56, 0x01 },// 选择顺时针旋转90°
            { 0x1b, 0x61, 0x30 },// 左对齐
            { 0x1b, 0x61, 0x31 },// 居中对齐
            { 0x1b, 0x61, 0x32 },// 右对齐
    };

    public PrintDataService(Context context, String deviceAddress) {
        super();
        this.context = context;
        this.deviceAddress = deviceAddress;
        this.device = this.bluetoothAdapter.getRemoteDevice(this.deviceAddress);
        try {
            this.bluetoothAdapter.listenUsingRfcommWithServiceRecord(this.getDeviceName(),uuid);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取设备名称
     *
     * @return String
     */
    public String getDeviceName() {
        return this.device.getName();
    }


    /**
     * 连接蓝牙设备
     */
    public boolean connect() {
        if (!this.isConnection) {
            try {
                if (bluetoothAdapter.isEnabled()){
                    Log.e("蓝牙", "蓝牙可用" );
                }else {
                    Log.e("蓝牙", "蓝牙不可用！" );
                    bluetoothAdapter.enable();
                }

                new Thread(){
                    @Override
                    public void run() {
                        try {
                            bluetoothSocket = device
                                    .createRfcommSocketToServiceRecord(uuid);
                            bluetoothSocket.connect();
                            outputStream = bluetoothSocket.getOutputStream();
                            isConnection = true;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();


                if (this.bluetoothAdapter.isDiscovering()) {
                    Log.e("蓝牙", "关闭适配器！");
                    this.bluetoothAdapter.isDiscovering();
                }
                SpUtils.saveBoolean(this.context,"islinked",true);
                Log.e("蓝牙", "蓝牙已连接1");

            } catch (Exception e) {
                SpUtils.saveBoolean(this.context,"islinked",false);
                Log.e("蓝牙", "Exception---->"+e.toString());
                return false;
            }

            return true;
        } else {
            SpUtils.saveBoolean(this.context,"islinked",true);
            Log.e("蓝牙", "蓝牙已连接2");
            return true;
        }
    }



    /**
     * 断开蓝牙设备连接
     */
    public static void disconnect() {
        System.out.println("断开蓝牙设备连接");
        try {
            bluetoothSocket.close();
            outputStream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * 选择指令
     */
    public void selectCommand() {
        new AlertDialog.Builder(context).setTitle("请选择指令")
                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            outputStream.write(byteCommands[which]);
                        } catch (IOException e) {
                            Toast.makeText(context, "设置指令失败！",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                }).create().show();
    }

    /**
     * 发送数据
     */
    public void send(String sendData) {
        if (this.isConnection) {
            System.out.println("开始打印！！");
            try {
                byte[] data = sendData.getBytes("gbk");
                outputStream.write(data, 0, data.length);
                outputStream.flush();
            } catch (IOException e) {
//                Toast.makeText(this.context, "发送失败！", Toast.LENGTH_SHORT)
//                        .show();
            }
        } else {
            connect();
//            Toast.makeText(this.context, "设备未连接，请重新连接！", Toast.LENGTH_SHORT)
//                    .show();


        }
    }


    public  void  sendText(List<OrderGoodsBean> mList,int ispack,String num){
        if (this.isConnection) {

            System.out.println("开始打印！！");
            try {
                outputStream.write(byteCommands[13]);
                outputStream.write(byteCommands[4]);

                String str="";
                str=" \n \n"+ "点菜单\n";
                str=str+"----------------"+ " \n";
//                outputStream.write(byteCommands[13]);
                str=str+"牌号: "+num+ " \n";
                str=str+"桌台:自助机"+ " \n";
                SimpleDateFormat df = new SimpleDateFormat("HH:mm");// 设置日期格式
                str=str+"时间:"+df.format(new Date())+ " \n";
                str=str+"----------------"+ " \n";

//                str=str+"------------------------"+ "\n";
                for (int i=0;i<mList.size();i++){
                    str=str+(i+1)+"、"+mList.get(i).getName()+"     *"+mList.get(i).getCount()+"\n";
                }
                str=str+"----------------"+ " \n";

                if (ispack==1){
                    str=str+"*打包"+"\n\n\n";

                }else{
                    str=str+"堂食"+"\n\n\n";
                }
                byte[] data = str.getBytes("gbk");
                outputStream.write(data, 0, data.length);
                outputStream.flush();


//                Bitmap bitmap = BitmapFactory.decodeStream(is);
//                Bitmap bitmapTo = PicFromPrintUtils.compressPic(bitmap);
//                outputStream.write(byteCommands[14]);
//                // 发送打印图片前导指令
//                byte[] start = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1B,
//                        0x40, 0x1B, 0x33, 0x00 };
//                outputStream.write(start);
//
//
//                byte[] draw2PxPoint = PicFromPrintUtils.pic2PxPoint(bitmapTo);
//
//                outputStream.write(draw2PxPoint);
//                // 发送结束指令
//                byte[] end = { 0x1d, 0x4c, 0x1f, 0x00 };
//                outputStream.write(end);
//                String str2="  \n \n";
//                byte[] data2 = str2.getBytes("gbk");
//                outputStream.write(data2, 0, data2.length);
//                outputStream.flush();
            } catch (Exception e) {
                Toast.makeText(this.context, "发送失败！", Toast.LENGTH_SHORT)
                        .show();
            }

        }else {
            Toast.makeText(this.context, "蓝牙打印机未连接，请重新连接！", Toast.LENGTH_SHORT)
                    .show();
        }
    }


}